package com.meida.student.app.scholartyrant.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.entity.BusOrderAnswer;
import com.meida.module.bus.client.entity.BusSubject;
import com.meida.module.bus.client.entity.BusTutorType;
import com.meida.module.bus.client.enums.AnswerStateEnum;
import com.meida.module.bus.client.enums.OrderStateZEnum;
import com.meida.module.bus.client.enums.ScholarTyrantOrderSearchStateEnum;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.bus.provider.service.BusSubjectService;
import com.meida.module.bus.provider.service.BusTutorTypeService;
import com.meida.module.bus.provider.utils.MyDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 学霸已接单订单列表分页扩展
 */
@Component
public class ScholartyrantOrderPageListHandler implements PageInterceptor<BusOrder> {

    @Autowired
    private BusSubjectService busSubjectService;

    @Autowired
    private BusOrderService busOrderService;

    @Autowired
    private BusTutorTypeService busTutorTypeService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public void prepare(CriteriaQuery<BusOrder> cq, PageParams pageParams, EntityMap params) {
        Integer orderState = params.getInt("orderState");
        Long answerUserId = OpenHelper.getUserId();
        cq.clear();
        cq.select(BusOrder.class, "orderId", "orderNo", "orderType", "appointmentDate", "appointmentTime", "durationTime", "subjectIds", "orderState", "coverImg", "answerUserId", "tutorTypeId", "orderDescribe", "rewardAmount", "commission", "createTime");
        cq.select(BusSubject.class, "subjectTitle");
        cq.select(BusOrderAnswer.class, "answerState");
        cq.eq(BusOrder.class, "orderType");
        cq.eq(BusOrderAnswer.class, "answerUserId", answerUserId);
        //进行中订单
        if (orderState == 0) {
            cq.and(true, q -> {
                q.like("orderState", OrderStateZEnum.OrderState1.getValue());
                q.or().like("orderState", 2);
                q.or().like("orderState", 3);
                q.or().like("orderState", 4);
                q.or().like("orderState", 6);
            });
            cq.ne(true, "answerState", 1);
            //定义学霸(我的任务进行中状态)
            Integer orderDetailState = params.getInt("orderDetailState");
            //待作答
            if (orderDetailState == ScholarTyrantOrderSearchStateEnum.orderDetailState1.getValue()) {
                cq.eq("orderState", 2);
            }
            //待审核
            if (orderDetailState == ScholarTyrantOrderSearchStateEnum.orderDetailState2.getValue()) {
                cq.eq("answerState", 0);
            }
            //审核通过
            if (orderDetailState == ScholarTyrantOrderSearchStateEnum.orderDetailState3.getValue()) {
                cq.eq("answerState", 2);
            }
            //审核失败
            if (orderDetailState == ScholarTyrantOrderSearchStateEnum.orderDetailState4.getValue()) {
                cq.eq("answerState", 3);
            }
            //已出价
            if (orderDetailState == ScholarTyrantOrderSearchStateEnum.orderDetailState5.getValue()) {
                cq.isNotNull("quotedPrice");
            }
            //待上课
            if (orderDetailState == ScholarTyrantOrderSearchStateEnum.orderDetailState6.getValue()) {
                cq.eq("orderState", "Y2");
            }
            //上课中
            if (orderDetailState == ScholarTyrantOrderSearchStateEnum.orderDetailState7.getValue()) {
                cq.eq("orderState", "Y3");
            }
            //售后处理
            if (orderDetailState == ScholarTyrantOrderSearchStateEnum.orderDetailState8.getValue()) {
                cq.eq("orderState", 6);
            }
        }
        //已完成订单
        if (orderState == 2) {
            cq.in("orderState", 5, 7);
            //未删除
            cq.eq("orderAnswer.deleted", 0);
        }
        //审核中订单
        if (orderState == 1) {
            cq.eq(BusOrderAnswer.class, "answerState", AnswerStateEnum.checkIng.getValue());
        }
        cq.createJoin(BusSubject.class).setMainField("subjectId").setJoinField("subjectId");
        cq.createJoin(BusOrderAnswer.class).setMainField("orderId").setJoinField("orderId");
    }

    @Override
    public void complete(CriteriaQuery<BusOrder> cq, List<EntityMap> result, EntityMap extra) {
        for (EntityMap entityMap : result) {
            String orderState = entityMap.get("orderState");
            Long orderId = entityMap.getLong("orderId");
            Integer orderType = entityMap.getInt("orderType");
            Integer answerState = entityMap.getInt("answerState");
            Long answerUserId = entityMap.getLong("answerUserId");
            Map orderStateDesc = busOrderService.getOrderStateDesc1(orderId, orderType, orderState, answerUserId, answerState);
            entityMap.putAll(orderStateDesc);
            String subjectIds = entityMap.get("subjectIds");
            List<String> subjectTitles = busSubjectService.selectSubjectTitles(subjectIds);
            entityMap.put("subjectTitles", subjectTitles);
            //todo 格式化时间
            Long tutorTypeId = entityMap.getLong("tutorTypeId");
            //辅导类型
            BusTutorType tutorType = busTutorTypeService.getById(tutorTypeId);
            if (FlymeUtils.isNotEmpty(tutorType)) {
                String tutorTypeName = tutorType.getTutorTypeName();
                Integer chargeType = tutorType.getChargeType();
                BigDecimal tutorPrice = tutorType.getTutorPrice();
                BigDecimal durationTime = entityMap.getBigDecimal("durationTime");
                if (chargeType.equals(1)) {
                    durationTime = durationTime.setScale(0, RoundingMode.HALF_UP);
                }
                String priceUnit = tutorType.getPriceUnit();
                String tutorTitle = MessageFormat.format("{0}(${1}/{2})", tutorTypeName, tutorPrice, priceUnit);
                entityMap.put("tutorTitle", tutorTitle);
                entityMap.put("durationTime", durationTime + priceUnit);
                String appointmentDate = entityMap.get("appointmentDate");
                String appointmentTime = entityMap.get("appointmentTime");
                String targetTimezone = httpServletRequest.getHeader("targetTimezone");
                if (FlymeUtils.isNotEmpty(appointmentDate)) {
                    String appointmentDateTimeStr = appointmentDate + " " + appointmentTime + ":00";
                    Date date = DateUtils.strToDate(appointmentDateTimeStr, "yyyy-MM-dd HH:mm:ss");
                    Date newDate = MyDateUtils.convertTimezone(date, targetTimezone);
                    String newAppointmentDate = DateUtils.formatDate(newDate, "yyyy-MM-dd");
                    String newAppointmentTime = DateUtils.formatDate(newDate, "HH:mm");
                    String dayOfWeek = DateUtils.getDayOfWeek(DateUtils.formatDate(newAppointmentDate));
                    entityMap.put("dayOfWeek", dayOfWeek);
                    entityMap.put("appointmentDate", newAppointmentDate);
                    entityMap.put("appointmentTime", newAppointmentTime);
                }
            }
        }
    }

}
